import React from 'react';
import {StyleSheet, View} from 'react-native';
import Toast from 'react-native-easy-toast';

import auth from '../../../common/auth';

import Header from '../../../components/header';
import Form from './form';
import api from '../../../common/api';

export default class extends React.Component {
    state = {
        userInfo: {},
        isFetching: false
    };

    //提交登录
    submit = nickname => {
        const {isFetching, userInfo} = this.state;
        if (isFetching) {
            return;
        }
        if (!nickname) {
            this.showToast('请填写昵称');
            return;
        }
        this.setState({
            isFetching: true
        });
        api({url: 'api/member/updateUserInfo', data: {nickname}})
            .then(() => {
                auth.setUserInfo({
                    ...userInfo,
                    nickname
                })
                    .then(() => {
                        auth.goBack();
                    });
            })
            .catch(e => {
                console.log(e);
                this.showToast(e.msg);
            })
            .finally(() => {
                this.setState({
                    isFetching: false
                });
            });
    };

    //toast弹出
    showToast = (text, time = 1000) => {
        this.refs.toast.show(text, time);
    };

    componentDidMount() {
        auth.getUserInfo()
            .then(userInfo => {
                this.setState({
                    userInfo: userInfo
                });
            })
            .catch(() => {
                auth.goBack();
            });
    }

    render() {
        const {userInfo} = this.state;
        return (
            <View style={styles.container}>
                <Header title="昵称"/>
                <Form submit={this.submit} userInfo={userInfo}/>
                <Toast ref="toast" position="center"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f0f0f0',
        flex: 1
    }
});
